//
//  KSMultiSelectUtil.swift
//  Slaughter
//
//  Created by 邱仙凯 on 2019/9/19.
//  Copyright © 2019 zwb. All rights reserved.
//

import UIKit
import JJCollectionViewRoundFlowLayout_Swift
struct MultiSeItem {
    var model:Any
    var selectedx:Bool
    var shot:UIImage?
    var indxId = 0
     init(model: Any, selectedx: Bool, shot: UIImage?) {
        self.model = model
        self.selectedx = selectedx
        self.shot = shot
     }
}
enum SelShowType {
    case flash,text// 选中内容快照型，选中内容文本型
}
class KSMultiSelectUtil: UITableViewController,UISearchBarDelegate {
    
    lazy var collectionView:UICollectionView = {
        // 1.创建layout
        
        let layout = JJCollectionViewRoundFlowLayout_Swift()
        layout.minimumLineSpacing = 8
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        
        // 2.创建UICollectionView
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 140), collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(MultiSeImgCell.self, forCellWithReuseIdentifier: MultiSeImgCell.identifier)
        collectionView.register(MultiSeTextCell.self, forCellWithReuseIdentifier: MultiSeTextCell.identifier)
        return collectionView
    }()
    static func initWithNav(title:String,
                            allArr:[(Any,Bool)],
                            controlClosure:(([Any])->(Bool))? = nil,
                            backClosure:@escaping (([Any])->()),
                            kSShowCell:((GlobalTableViewCell,Any)->())?,
                            filterClosure:((Any,String)->(Bool))?,
                            kSSelShowCell:((MultiSeTextCell,Any)->())? = nil) -> UIViewController {
        
        let nav = BaseNavigationController()
        let vc = KSMultiSelectUtil(title: title, allArr: allArr,controlClosure: controlClosure, backClosure: backClosure,kSListShowCell:kSShowCell,filterClosure: filterClosure,kSSelShowCell: kSSelShowCell)
        nav.viewControllers = [vc]
        return nav
    }
    // 植入的校验方法
    private var controlClosure:(([Any])->(Bool))?
    // 过滤方法外部辅助实现
    private var filterClosure:((Any,String)->(Bool))?
    // cell 展示外部注入
     var kSListShowCell:((GlobalTableViewCell,Any)->())?
    
    
    // item选中后的头部显示效果，外部注入
    var kSSelShowCell:((MultiSeTextCell,Any)->())?
    
    var allArr = [(Any,Bool)]()
    private var tempArr = [MultiSeItem]()
    private var collSelArr = [MultiSeItem]()

    var backClosure:([Any])->()
    
    private var keyWord = ""
    private lazy var searchBar:UISearchBar = {
       let v = UISearchBar(frame:CGRect(x:0,y:0,width:self.view.frame.width,height:40))
        v.placeholder = "搜索"
        v.backgroundColor = .clear
        v.backgroundImage = UIImage()
        return v
    }()
    private lazy var allSeBtn:AllButton = {
        let  btn = AllButton(frame:CGRect(x:0,y:40,width:self.view.frame.width,height:32))
        return btn
    }()
    private lazy var headerV:UIView = {
        // 头部视图
        let   v = UIView(frame: CGRect(x:0,y:0,width:self.view.frame.width,height: 165))
        v.backgroundColor = #colorLiteral(red: 0.9607843137, green: 0.9607843137, blue: 0.9607843137, alpha: 1)
        return v
    }()
    lazy var blockV:UIView = {
       let v = UIView()
        v.backgroundColor = UIColor(kshex: "4972F9")
        return v
    }()
    
    init(title:String,
         allArr:[(Any,Bool)],
         controlClosure:(([Any])->(Bool))? = nil,
         backClosure:@escaping (([Any])->()),
         kSListShowCell:((GlobalTableViewCell,Any)->())?,
         filterClosure:((Any,String)->(Bool))?,
         kSSelShowCell:((MultiSeTextCell,Any)->())?) {
        self.allArr = allArr
        self.backClosure = backClosure
          self.controlClosure = controlClosure
        self.kSListShowCell = kSListShowCell
        self.kSSelShowCell = kSSelShowCell
        self.filterClosure = filterClosure
        super.init(nibName: nil, bundle: nil)
        self.title = title
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let leftbtn = UIButton.creat4Item(title: "返回") { _ in
            self.dismiss(animated: true, completion: {
            })
        }
        let left = UIBarButtonItem(customView:leftbtn)
      
        self.navigationItem.leftBarButtonItem = left
        self.tableView.backgroundColor = Theme.awModuleBgColor
        self.tableView.separatorStyle = .none
        self.tableView.estimatedRowHeight = 100
        self.tableView.rowHeight = UITableView.automaticDimension
        tableView.register(GlobalTableViewCell.self, forCellReuseIdentifier: GlobalTableViewCell.identifier)

        let rightBtn = UIButton.creat4Item(title: "确定") { _ in
            
            let xxx = self.tempArr.filter { $0.selectedx == true }
            guard xxx.count > 0 else {
                KSToast("未选中任意项")
                return
            }
            if let clo = self.controlClosure {
                
                guard clo(xxx.compactMap{$0.model}) else {
                    return
                }
              }
 
            self.backClosure(xxx.compactMap{$0.model})
            self.dismiss(animated: true, completion: {
            })
        }
        
        let right = UIBarButtonItem(customView: rightBtn)
       
        
        
        self.navigationItem.rightBarButtonItem = right
        
        
     
        searchBar.inputAccessoryView = KSToolbar(controller: self)
        searchBar.delegate = self

        tableView.register(KSMultiSelectCell.self, forCellReuseIdentifier: KSMultiSelectCell.identifier)
 
         
        tableView.tableFooterView = UIView()
 
      
         
        self.filterData()
        

     
        // 全选点击事件
        allSeBtn.addTouchUpInSideAction { _ in
            self.allSeBtn.isSelected = !self.allSeBtn.isSelected
            
            for i in 0..<self.tempArr.count {
                self.tempArr[i].selectedx = self.allSeBtn.isSelected
            }
            self.configHeader()
            self.tableView.reloadData()
        }
        headerV.addSubview(searchBar)
        let headBottomBg = UIView()
        headBottomBg.backgroundColor = .white
        headBottomBg.layer.cornerRadius = 6
        headerV.addSubview(headBottomBg)
        headBottomBg.snp.makeConstraints({ make in
            make.left.equalToSuperview().offset(8)
            make.right.equalToSuperview().offset(-8)
            make.bottom.equalToSuperview().offset(-2)
            make.top.equalTo(searchBar.snp.bottom).offset(3)
        })
        headBottomBg.addSubview(blockV)
        headBottomBg.addSubview(allSeBtn)
        collectionView.delegate = self
        collectionView.dataSource = self
      
        headBottomBg.addSubview(collectionView)
        searchBar.snp.makeConstraints({ make in
            make.left.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(40)
            make.top.equalToSuperview().offset(3)
        })
        blockV.snp.makeConstraints { make in
          make.left.equalToSuperview().offset(5)
            make.width.equalTo(3)
            make.height.equalTo(15)
            make.top.equalToSuperview().offset(10)
      }
        allSeBtn.snp.makeConstraints({ make in
            make.left.equalTo(blockV.snp.right).offset(8)
            make.width.equalTo(180)
            make.height.equalTo(32)
            make.centerY.equalTo(blockV)
        })
        collectionView.snp.makeConstraints({ make in
            make.left.equalToSuperview().offset(8)
            make.right.equalToSuperview().offset(-8)
            make.bottom.equalToSuperview().offset(-2)
            make.top.equalTo(allSeBtn.snp.bottom).offset(3)
        })
        
        self.configHeader()
    }
    func dealCollData() {
        self.collSelArr.removeAll()
        for i in 0..<self.tempArr.count {
            let onex = self.tempArr[i]
            if onex.selectedx {
                var temponex = onex
                temponex.indxId = i
                self.collSelArr.append(temponex)
             }
         }
        
        if self.kSSelShowCell.isSome {
            if self.collSelArr.count < 6 {
                self.headerV.ks_height = 130
            } else {
                self.headerV.ks_height = 170
             }
        } else {
            
            if self.collSelArr.count < 6 {
                self.headerV.ks_height = 165
            } else {
                self.headerV.ks_height = 225
             }
        }
      
        self.collectionView.reloadData()
        
     
        
        
    }
    func configHeader() {
        var allSelected = true
        var selectedCount = 0
        self.tempArr.forEach {
            if $0.selectedx == false {
                allSelected = false
            } else {
                selectedCount += 1
            }
        }
        self.allSeBtn.isSelected = allSelected
        let str = "选择信息（共\(self.tempArr.count)项，已选\(selectedCount)项）"
        self.allSeBtn.setTitle(str, for: .normal)
        self.dealCollData()
 
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return self.headerV.ks_height
    }
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return headerV
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return tempArr.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: GlobalTableViewCell.identifier, for: indexPath) as!
        GlobalTableViewCell
        if let clo = kSListShowCell {
            clo(cell,self.tempArr[indexPath.row].model)
        }
        cell.cellSelectable = true
        cell.setSelect(tempArr[indexPath.row].selectedx)
 
         return cell
        
        
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! GlobalTableViewCell
        let one = self.tempArr[indexPath.row]
        if one.selectedx == true {
            self.tempArr[indexPath.row].selectedx = false
         } else {
             self.tempArr[indexPath.row].selectedx = true
             
             if self.kSSelShowCell.isNone {
                 if self.tempArr[indexPath.row].shot.isNone {
                     // 生成快照
                     if let snapshot = captureThumbnail(of: cell) {
                          self.tempArr[indexPath.row].shot = snapshot
                       }
                 }
              
             }
      
             
             
         }
         self.configHeader()
        self.tableView.reloadData()
        
        
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        keyWord = searchText
        self.filterData()
    }
    
    func filterData() {
        
        tempArr.removeAll()
        if keyWord != "" {
 
             self.allArr.forEach {
                  if let clo = self.filterClosure {
                      if clo($0.0,keyWord) {
                          tempArr.append(MultiSeItem(model: $0.0, selectedx: $0.1, shot: nil))
                     }
                  } else {
                      tempArr.append(MultiSeItem(model: $0.0, selectedx: $0.1, shot: nil))
 
                  }
             }
        } else {
            tempArr = self.allArr.compactMap{ MultiSeItem(model: $0.0, selectedx: $0.1, shot: nil) }
        }
        
        self.tableView.reloadData()
        self.configHeader()
    }
    
    
    
}
// MARK: -   代理和数据源
extension KSMultiSelectUtil:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      
        return self.collSelArr.count
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if self.kSSelShowCell.isSome {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MultiSeTextCell.identifier, for: indexPath as IndexPath) as! MultiSeTextCell
            
            let one = self.collSelArr[indexPath.row]
            kSSelShowCell!(cell,one.model)
      
            cell.btn.addTouchUpInSideAction { _ in
     
                self.tempArr[one.indxId].selectedx = false
     
                self.tableView.reloadData()
                self.configHeader()
     
                
            }
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MultiSeImgCell.identifier, for: indexPath as IndexPath) as! MultiSeImgCell
            
            let one = self.collSelArr[indexPath.row]
            if one.shot.isSome {
                cell.btn.setBackgroundImage(one.shot!, for: .normal)
            }

            cell.deleteBtn.addTouchUpInSideAction { _ in
     
                self.tempArr[one.indxId].selectedx = false
     
                self.tableView.reloadData()
                self.configHeader()
     
                
            }
            return cell
        }
      
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        
    }
    
    
    // 设置itemsize
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let sectionW = self.view.ks_width - 70
        var itemW:CGFloat = 0
        var itemH:CGFloat = 0
        if self.kSSelShowCell.isSome {
             itemW = sectionW/4 - 0.5
            itemH = 30
        } else {
             itemW = sectionW/5 - 0.5
            itemH = sectionW/5 - 0.5
        }
  
        return CGSize(width: itemW, height: itemH)
        
    }
    
    
}
extension KSMultiSelectUtil : JJCollectionViewDelegateRoundFlowLayout_Swift{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, borderEdgeInsertsForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 12, left: 12, bottom: 12, right: 12)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, configModelForSectionAtIndex section: Int) -> JJCollectionViewRoundConfigModel_Swift {
        if section == 0 {
            let model = JJCollectionViewRoundConfigModel_Swift.init()
            model.cornerRadius = 8
            model.backgroundColor = .clear
            return model
        } else {
            let model = JJCollectionViewRoundConfigModel_Swift.init()
            return model
        }
        
        
        
    }
}

